#!/usr/bin/env bash

#-----------------------------------------------------------------------------------------------------
# Nodejs 下载地址
#   镜像1: https://nodejs.org/dist/ (https://nodejs.org/dist/v16.18.0/node-v16.18.0-linux-x64.tar.gz)
# OracleJDK 下载地址
#   镜像1: https://www.injdk.cn/ (https://d6.injdk.cn/oraclejdk/11/jdk-11.0.16.1_linux-x64_bin.tar.gz) (https://d6.injdk.cn/oraclejdk/8/jdk-8u341-linux-x64.tar.gz)
#   镜像2: http://www.codebaoku.com/jdk/jdk-index.html (https://114-233-56-217.d.cjjd09.com:30443/123-511/85b2a0b8/1661483-0/85b2a0b8c16863b3ad55e742ac2ba9ff?v=3&t=1667188559&s=f2df45083bb69864446f801bf25b725c&i=dde8a980&filename=jdk-11.0.15.1_linux-x64_bin.tar.gz&d=6ee52da1)
# Gradle 下载地址
#   官方: https://gradle.org/releases/
# Maven 下载地址
#   官方: https://maven.apache.org/docs/history.html
#-----------------------------------------------------------------------------------------------------

# 配置
ADD_USER_NAME="www"
ADD_USER_PASSWORD="MoXF2Zi6u7f7lqZu"
BASE_DIR="/opt"

# 软件
YUM_REPOS="http://mirrors.aliyun.com/repo/Centos-7.repo"
#--- nodejs (setup_16.x | setup_18.x | setup_20.x)
NODEJS_URL="https://rpm.nodesource.com/setup_16.x"
#--- jdk(安装)
JDK_URL="http://all.msvc.top:30005/public/app-pkgs/raw/branch/main/OracleJDK/jdk-8u202-linux-x64.tar.gz"
#--- jdk8(参考)
JDK8_URL="http://all.msvc.top:30005/public/app-pkgs/raw/branch/main/OracleJDK/jdk-8u411-linux-x64.tar.gz"
#--- jdk11(参考)
JDK11_URL="http://all.msvc.top:30005/public/app-pkgs/raw/branch/main/OracleJDK/jdk-11.0.23_linux-x64_bin.tar.gz"
#--- jdk17(参考)
JDK17_URL="http://all.msvc.top:30005/public/app-pkgs/raw/branch/main/OracleJDK/jdk-17.0.11_linux-x64_bin.tar.gz"
#--- jdk21(参考)
JDK21_URL=""
#--- gradle (6.8.3 | 6.9.4 | 7.6.3 | 8.2.1)
GRADLE_URL="http://all.msvc.top:30005/public/app-pkgs/raw/branch/main/Gradle/gradle-6.8.3-bin.zip"
#--- maven (3.8.8 | 3.9.6)
MAVEN_URL="https://dlcdn.apache.org/maven/maven-3/3.9.6/binaries/apache-maven-3.9.6-bin.tar.gz"
#--- jenkins (http://mirrors.jenkins.io/war-stable/latest/)
JENKINS_JAVA_URL="https://d6.injdk.cn/oraclejdk/21/jdk-21_linux-x64_bin.tar.gz"
JENKINS_URL="https://ftp-nyc.osuosl.org/pub/jenkins/war-stable/latest/jenkins.war"
#--- redis Latest Stable
REDIS_URL="https://download.redis.io/redis-stable.tar.gz"

# 安装标识
#--- SSH用户
SSH_OPTIONS="-o ConnectTimeout=600 -o StrictHostKeyChecking=no -o UserKnownHostsFile=/dev/null"
SSH_USER=""
SSH_PASSWORD=""
SSH_PRIVATE_KEY=""
SSH_PORT=""
#--- SUDO用户
SUDO_TAG="0"
SUDO_USER=""
SUDO_PASSWORD=""
#--- 指令
INIT_TAG="0"
#--- 指令参数
UPDATE_YUM_REPOS="0"
CONFIG_TAG="0"
ADD_USER_TAG="0"
GIT_TAG="0"
DSTAT_TAG="0"
HTOP_TAG="0"
NGINX_TAG="0"
NODEJS_TAG="0"
JAVA_TAG="0"
GRADLE_TAG="0"
MAVEN_TAG="0"
JENKINS_TAG="0"
REDIS_TAG="0"

# 脚本设置
TMP_DIR="$(rm -rf /tmp/env-install* && mktemp -d -t env-install.XXXXXXXXXX)"
LOG_FILE="${TMP_DIR}/env-install.log"
ERROR_INFO="\n\033[31mERROR Summary: \033[0m\n  "
ACCESS_INFO="\n\033[32mACCESS Summary: \033[0m\n  "
SCRIPT_PARAMETER="$*"
COMMAND_OUTPUT=""

######################################################################################################
# 通用函数
######################################################################################################
# 信号处理
function trap::info() {
  [[ ${#ERROR_INFO} -gt 37 ]] && echo -e "$ERROR_INFO"
  [[ ${#ACCESS_INFO} -gt 38 ]] && echo -e "$ACCESS_INFO"
  [ -f "$LOG_FILE" ] && echo -e "\n\n  See detailed log >>> cat $LOG_FILE \n\n"
  trap '' EXIT
  exit
}

# 错误日志
function log::error() {
  local item; item="[$(date +'%Y-%m-%dT%H:%M:%S.%N%z')]: \033[31mERROR:   \033[0m$*"
  ERROR_INFO="${ERROR_INFO}${item}\n  "
  echo -e "${item}" | tee -a "$LOG_FILE"
}

# 基础日志
function log::info() {
  printf "[%s]: \033[32mINFO:    \033[0m%s\n" "$(date +'%Y-%m-%dT%H:%M:%S.%N%z')" "$*" | tee -a "$LOG_FILE"
}

# 警告日志
function log::warning() {
  printf "[%s]: \033[33mWARNING: \033[0m%s\n" "$(date +'%Y-%m-%dT%H:%M:%S.%N%z')" "$*" | tee -a "$LOG_FILE"
}

# 访问信息
function log::access() {
  ACCESS_INFO="${ACCESS_INFO}$*\n  "
  printf "[%s]: \033[32mINFO:    \033[0m%s\n" "$(date +'%Y-%m-%dT%H:%M:%S.%N%z')" "$*" | tee -a "$LOG_FILE"
}

# 执行日志
function log::exec() {
  printf "[%s]: \033[34mEXEC:    \033[0m%s\n" "$(date +'%Y-%m-%dT%H:%M:%S.%N%z')" "$*" >> "$LOG_FILE"
}

# 检查返回码
function check::exit_code() {
  local code=${1:-}
  local app=${2:-}
  local desc=${3:-}
  local exit_script=${4:-}
  if [[ "${code}" == "0" ]]; then
    log::info "[${app}]" "${desc} succeeded."
  else
    log::error "[${app}]" "${desc} failed."
    [[ "$exit_script" == "exit" ]] && exit "$code"
  fi
}

# 重试
function utils::retry() {
  local retries=$1
  shift
  local count=0
  until eval "$*"; do
    exit=$?
    wait=$((2 ** count))
    count=$((count + 1))
    if [ "$count" -lt "$retries" ]; then
      echo "Retry $count/$retries exited $exit, retrying in $wait seconds..."
      sleep $wait
    else
      echo "Retry $count/$retries exited $exit, no more retries left."
      return $exit
    fi
  done
  return 0
}

# 转义引号
function utils::quote() {
  # shellcheck disable=SC2046
  if [ $(echo "$*" | tr -d "\n" | wc -c) -eq 0 ]; then
    echo "''"
  elif [ $(echo "$*" | tr -d "[a-z][A-Z][0-9]:,.=~_/\n-" | wc -c) -gt 0 ]; then
    printf "%s" "$*" | sed -e "1h;2,\$H;\$!d;g" -e "s/'/\'\"\'\"\'/g" | sed -e "1h;2,\$H;\$!d;g" -e "s/^/'/g" -e "s/$/'/g"
  else
    echo "$*"
  fi
}

# 检查命令是否存在
function check::command_exists() {
  local cmd=${1}
  local package=${2}
  if command -V "$cmd" > /dev/null 2>&1; then
    log::info "[check]" "$cmd command exists."
  else
    log::warning "[check]" "I require $cmd but it's not installed."
    log::warning "[check]" "install $package package."
    command::exec "127.0.0.1" "yum install -y ${package}"
    check::exit_code "$?" "check" "$package install" "exit"
  fi
}

# 执行命令
function command::exec() {
  local host=${1:-"127.0.0.1"}
  shift
  local command="$*"
  if [[ "${SUDO_TAG:-}" == "1" ]]; then
    sudo_options="sudo -H -n -u ${SUDO_USER}"
    if [[ "${SUDO_PASSWORD:-}" != "" ]]; then
       sudo_options="${sudo_options// -n/} -p \"\" -S <<< \"${SUDO_PASSWORD}\""
    fi
    command="$sudo_options bash -c $(utils::quote "$command")"
  fi
  command="$(utils::quote "$command")"
  if [[ "${host}" == "127.0.0.1" ]]; then
    # 本地执行
    log::exec "[command]" "bash -c $(printf "%s" "${command//${SUDO_PASSWORD:-}/zzzzzz}")"
    # shellcheck disable=SC2094
    COMMAND_OUTPUT=$(eval bash -c "${command}" 2>> "$LOG_FILE" | tee -a "$LOG_FILE")
    local status=$?
  else
    # 远程执行
    local ssh_cmd="ssh"
    if [[ "${SSH_PASSWORD}" != "" ]]; then
      ssh_cmd="sshpass -p \"${SSH_PASSWORD}\" ${ssh_cmd}"
    elif [[ "$SSH_PRIVATE_KEY" != "" ]]; then
      [ -f "${SSH_PRIVATE_KEY}" ] || { log::error "[exec]" "ssh private_key:${SSH_PRIVATE_KEY} not found."; exit 1; }
      ssh_cmd="${ssh_cmd} -i $SSH_PRIVATE_KEY"
    fi
    log::exec "[command]" "${ssh_cmd//${SSH_PASSWORD:-}/zzzzzz} ${SSH_OPTIONS} ${SSH_USER}@${host} -p ${SSH_PORT} bash -c $(printf "%s" "${command//${SUDO_PASSWORD:-}/zzzzzz}")"
    # shellcheck disable=SC2094
    COMMAND_OUTPUT=$(eval "${ssh_cmd} ${SSH_OPTIONS} ${SSH_USER}@${host} -p ${SSH_PORT}" bash -c '"${command}"' 2>> "$LOG_FILE" | tee -a "$LOG_FILE")
    local status=$?
  fi
  return $status
}

######################################################################################################
# 安装函数
######################################################################################################
# 检查用到的命令
function check::command() {
  check::command_exists ssh openssh-clients
  check::command_exists tar tar
  check::command_exists wget wget
  check::command_exists unzip unzip
}

# 更新yum源
function init:update_yum_repos() {
  log::info "[update-yum-repos]" "更新yum源..."
  local host="127.0.0.1"
  local repo="/etc/yum.repos.d/CentOS-Base.repo"
  local repo_bak="/etc/yum.repos.d/CentOS-Base.repo_bak"
  command::exec "${host}" "
    if [ ! -f "$repo_bak" ]; then
      mv $repo $repo_bak
      wget --timeout=10 --waitretry=3 --tries=5 --retry-connrefused --no-check-certificate ${YUM_REPOS} -O $repo
      yum clean all
      yum makecache
      yum -y install epel-release
    fi
  "
  check::exit_code "$?" "update-yum-repos" "$host 更新yum源" "exit"
  log::info "[update-yum-repos]" "yum源更新成功!"
}

# 系统配置
function init:config() {
  log::info "[config]" "关闭系统防火墙..."
  local host="127.0.0.1"
  command::exec "${host}" "
    # 停止防火墙
    systemctl stop firewalld
    # 彻底关闭防火墙
    systemctl disable firewalld
  "
  log::info "[config]" "系统防火墙关闭成功!"
}

# 新增用户
function init:add_user() {
  log::info "[add-user]" "新增用户[${ADD_USER_NAME}]..."
  local host="127.0.0.1"
  local add_sudoers="${ADD_USER_NAME}    ALL=(ALL)       NOPASSWD:ALL"
  command::exec "${host}" "
  id -u ${ADD_USER_NAME} >/dev/null 2>&1
  if [ \$? -ne '0' ]; then
    # 创建用户
    adduser ${ADD_USER_NAME}
    # 设置密码
    echo ${ADD_USER_NAME}:${ADD_USER_PASSWORD} | chpasswd
    # 禁止远程登录
    echo DenyUsers ${ADD_USER_NAME} >> /etc/ssh/sshd_config
  fi
  if [ \`grep -c '$add_sudoers' '/etc/sudoers'\` == '0' ];then
    # 新增修改权限
    chmod -v u+w /etc/sudoers
    echo -e '$add_sudoers' >> /etc/sudoers
    # 收回修改权限
    chmod -v u-w /etc/sudoers
  fi
  "
  check::exit_code "$?" "add-user" "$host 新增用户[${ADD_USER_NAME}]" "exit"
  log::info "[add-user]" "新增用户[${ADD_USER_NAME}]成功!"
}

# 安装git环境
function init:git() {
  log::info "[git]" "安装git环境..."
  local host="127.0.0.1"
  local exc_cmd="git config --global credential.helper store"
  command::exec "${host}" "
    yum -y install https://packages.endpointdev.com/rhel/7/os/x86_64/endpoint-repo.x86_64.rpm
    yum -y install git
    git --version
    $exc_cmd
  "
  check::exit_code "$?" "git" "$host 安装git环境" "exit"
  log::info "[git]" "git环境安装成功!"
  if [[ "${ADD_USER_TAG:-}" == "1" ]]; then
    command::exec "${host}" "
      echo '${ADD_USER_PASSWORD}' | su - ${ADD_USER_NAME} -c '$exc_cmd'
    "
    check::exit_code "$?" "git" "$host git配置" "exit"
    log::info "[git]" "git配置成功!"
  fi
}

# 安装dstat
function init:dstat() {
  log::info "[dstat]" "安装dstat..."
  local host="127.0.0.1"
  command::exec "${host}" "
    yum -y install dstat
    dstat -V
  "
  check::exit_code "$?" "dstat" "$host 安装dstat" "exit"
  log::info "[dstat]" "dstat安装成功!"
}

# 安装htop
function init:htop() {
  log::info "[htop]" "安装htop..."
  local host="127.0.0.1"
  command::exec "${host}" "
    yum -y install htop
    htop -v
  "
  check::exit_code "$?" "htop" "$host 安装htop" "exit"
  log::info "[htop]" "htop安装成功!"
}

# 安装nginx
function init:nginx() {
  log::info "[nginx]" "安装nginx..."
  local host="127.0.0.1"
  command::exec "${host}" "
    yum -y install nginx
    nginx -v
  "
  check::exit_code "$?" "nginx" "$host 安装nginx" "exit"
  log::info "[nginx]" "nginx安装成功!"
  log::info "[nginx]" "配置文件路径: /etc/nginx"
  log::info "[nginx]" "设置开机启动: sudo systemctl enable nginx"
  log::info "[nginx]" "启动/停止/重启: sudo service nginx start/stop/restart"
  log::info "[nginx]" "检查nginx配置: sudo nginx -t"
  log::info "[nginx]" "加载nginx配置: sudo nginx -s reload"
}

# 安装nodejs环境
function init:nodejs() {
  log::info "[nodejs]" "安装nodejs环境..."
  local host="127.0.0.1"
  command::exec "${host}" "
    curl -fsSL ${NODEJS_URL} | sudo bash -
    yum -y install nodejs
    yum -y install npm
    npm install --global yarn
    # 配置npm源
    npm config set registry https://registry.npm.taobao.org
    npm config set disturl https://npm.taobao.org/dist
    npm config set electron_mirror https://npm.taobao.org/mirrors/electron/
    npm config set sass_binary_site https://npm.taobao.org/mirrors/node-sass/
    npm config set phantomjs_cdnurl https://npm.taobao.org/mirrors/phantomjs/
    # 配置yarn源
    yarn config set registry https://registry.npm.taobao.org -g
    yarn config set disturl https://npm.taobao.org/dist -g
    yarn config set electron_mirror https://npm.taobao.org/mirrors/electron/ -g
    yarn config set sass_binary_site https://npm.taobao.org/mirrors/node-sass/ -g
    yarn config set phantomjs_cdnurl https://npm.taobao.org/mirrors/phantomjs/ -g
    yarn config set chromedriver_cdnurl https://cdn.npm.taobao.org/dist/chromedriver -g
    yarn config set operadriver_cdnurl https://cdn.npm.taobao.org/dist/operadriver -g
    yarn config set fse_binary_host_mirror https://npm.taobao.org/mirrors/fsevents -g
    # 验证
    node -v
    npm -v
    yarn -v
  "
  check::exit_code "$?" "nodejs" "$host 安装nodejs环境" "exit"
  if [[ "${ADD_USER_TAG:-}" == "1" ]]; then
    command::exec "${host}" "
      # 配置npm源
      echo '${ADD_USER_PASSWORD}' | su - ${ADD_USER_NAME} -c 'npm config set registry https://registry.npm.taobao.org'
      echo '${ADD_USER_PASSWORD}' | su - ${ADD_USER_NAME} -c 'npm config set disturl https://npm.taobao.org/dist'
      echo '${ADD_USER_PASSWORD}' | su - ${ADD_USER_NAME} -c 'npm config set electron_mirror https://npm.taobao.org/mirrors/electron/'
      echo '${ADD_USER_PASSWORD}' | su - ${ADD_USER_NAME} -c 'npm config set sass_binary_site https://npm.taobao.org/mirrors/node-sass/'
      echo '${ADD_USER_PASSWORD}' | su - ${ADD_USER_NAME} -c 'npm config set phantomjs_cdnurl https://npm.taobao.org/mirrors/phantomjs/'
      # 配置yarn源
      echo '${ADD_USER_PASSWORD}' | su - ${ADD_USER_NAME} -c 'yarn config set registry https://registry.npm.taobao.org -g'
      echo '${ADD_USER_PASSWORD}' | su - ${ADD_USER_NAME} -c 'yarn config set disturl https://npm.taobao.org/dist -g'
      echo '${ADD_USER_PASSWORD}' | su - ${ADD_USER_NAME} -c 'yarn config set electron_mirror https://npm.taobao.org/mirrors/electron/ -g'
      echo '${ADD_USER_PASSWORD}' | su - ${ADD_USER_NAME} -c 'yarn config set sass_binary_site https://npm.taobao.org/mirrors/node-sass/ -g'
      echo '${ADD_USER_PASSWORD}' | su - ${ADD_USER_NAME} -c 'yarn config set phantomjs_cdnurl https://npm.taobao.org/mirrors/phantomjs/ -g'
      echo '${ADD_USER_PASSWORD}' | su - ${ADD_USER_NAME} -c 'yarn config set chromedriver_cdnurl https://cdn.npm.taobao.org/dist/chromedriver -g'
      echo '${ADD_USER_PASSWORD}' | su - ${ADD_USER_NAME} -c 'yarn config set operadriver_cdnurl https://cdn.npm.taobao.org/dist/operadriver -g'
      echo '${ADD_USER_PASSWORD}' | su - ${ADD_USER_NAME} -c 'yarn config set fse_binary_host_mirror https://npm.taobao.org/mirrors/fsevents -g'
    "
    check::exit_code "$?" "nodejs" "$host nodejs配置" "exit"
    log::info "[nodejs]" "nodejs配置成功!"
  fi
  log::info "[nodejs]" "安装nodejs环境成功!"
}

# 安装java环境
function init:java() {
  log::info "[java]" "安装java环境..."
  local host="127.0.0.1"
  local tmp_download="tmp_download"
  local tmp_dir="tmp"
  local java_path="${BASE_DIR}/java/install_java.txt"
  command::exec "${host}" "
    yum -y remove *openjdk*
    if [ ! -f "$java_path" ]; then
      mkdir -p ${BASE_DIR}/java
      cd ${BASE_DIR}/java
      rm -rf ./${tmp_download}
      mkdir ./${tmp_download}
      cd ./${tmp_download}
      wget --timeout=10 --waitretry=3 --tries=5 --retry-connrefused --no-check-certificate ${JDK_URL}
      file_name=\`ls ./ | head -n 1\`
      if [ -z \$file_name ];then
        echo '下载失败=${JDK_URL}'
        cd ../
      else
        mkdir ./${tmp_dir}
        tar -zxvf \$file_name -C ./${tmp_dir}
        mv \$file_name ../\$file_name
        cd ./${tmp_dir}
        file_name=\`ls ./ | head -n 1\`
        mv \$file_name ../../\$file_name
        cd ../../
        line=\"\n\"
        add_profile=\`echo -e \"\${line}JAVA_HOME=${BASE_DIR}/java/\$file_name\${line}PATH=\\\\\$JAVA_HOME/bin:\\\\\$PATH\${line}export JAVA_HOME PATH\"\`
        echo \"\$add_profile\" >> /etc/profile
        source /etc/profile
        echo \"\$file_name\" >> ${java_path}
      fi
      rm -rf ./${tmp_download}
    fi
    java -version
  "
  check::exit_code "$?" "java" "$host 安装java环境" "exit"
  if [[ "${ADD_USER_TAG:-}" == "1" ]]; then
    command::exec "${host}" "
      sudo chown -R \$(id -u ${ADD_USER_NAME}):\$(id -g ${ADD_USER_NAME}) ${BASE_DIR}/java
    "
  fi
  log::info "[java]" "java环境安装成功!系统环境配置: /etc/profile"
}

# 安装gradle环境
function init:gradle() {
  log::info "[gradle]" "安装gradle环境..."
  local host="127.0.0.1"
  local tmp_download="tmp_download"
  local tmp_dir="tmp"
  local gradle_path="${BASE_DIR}/gradle/install_gradle.txt"
  command::exec "${host}" "
    if [ ! -f "$gradle_path" ]; then
      mkdir -p ${BASE_DIR}/gradle
      cd ${BASE_DIR}/gradle
      rm -rf ./${tmp_download}
      mkdir ./${tmp_download}
      cd ./${tmp_download}
      wget --timeout=10 --waitretry=3 --tries=5 --retry-connrefused --no-check-certificate ${GRADLE_URL}
      file_name=\`ls ./ | head -n 1\`
      if [ -z \$file_name ];then
        echo '下载失败=${GRADLE_URL}'
        cd ../
      else
        mkdir ./${tmp_dir}
        unzip \$file_name -d ./${tmp_dir}
        mv \$file_name ../\$file_name
        cd ./${tmp_dir}
        file_name=\`ls ./ | head -n 1\`
        mv \$file_name ../../\$file_name
        cd ../../
        line=\"\n\"
        add_profile=\`echo -e \"\${line}GRADLE_HOME=${BASE_DIR}/gradle/\$file_name\${line}PATH=\\\\\$GRADLE_HOME/bin:\\\\\$PATH\${line}export GRADLE_HOME PATH\"\`
        echo \"\$add_profile\" >> /etc/profile
        source /etc/profile
        echo \"\$file_name\" >> ${gradle_path}
      fi
      rm -rf ./${tmp_download}
    fi
    gradle -v
  "
  check::exit_code "$?" "gradle" "$host 安装gradle环境" "exit"
  if [[ "${ADD_USER_TAG:-}" == "1" ]]; then
    command::exec "${host}" "
      sudo chown -R \$(id -u ${ADD_USER_NAME}):\$(id -g ${ADD_USER_NAME}) ${BASE_DIR}/gradle
    "
  fi
  log::info "[gradle]" "gradle环境安装成功!系统环境配置: /etc/profile"
}

# 安装maven环境
function init:maven() {
  log::info "[maven]" "安装maven环境..."
  local host="127.0.0.1"
  local tmp_download="tmp_download"
  local tmp_dir="tmp"
  local maven_path="${BASE_DIR}/maven/install_maven.txt"
  command::exec "${host}" "
    if [ ! -f "$maven_path" ]; then
      mkdir -p ${BASE_DIR}/maven
      cd ${BASE_DIR}/maven
      rm -rf ./${tmp_download}
      mkdir ./${tmp_download}
      cd ./${tmp_download}
      wget --timeout=10 --waitretry=3 --tries=5 --retry-connrefused --no-check-certificate ${MAVEN_URL}
      file_name=\`ls ./ | head -n 1\`
      if [ -z \$file_name ];then
        echo '下载失败=${MAVEN_URL}'
        cd ../
      else
        mkdir ./${tmp_dir}
        tar -zxvf \$file_name -C ./${tmp_dir}
        mv \$file_name ../\$file_name
        cd ./${tmp_dir}
        file_name=\`ls ./ | head -n 1\`
        mv \$file_name ../../\$file_name
        cd ../../
        line=\"\n\"
        add_profile=\`echo -e \"\${line}MAVEN_HOME=${BASE_DIR}/maven/\$file_name\${line}PATH=\\\\\$MAVEN_HOME/bin:\\\\\$PATH\${line}export MAVEN_HOME PATH\"\`
        echo \"\$add_profile\" >> /etc/profile
        source /etc/profile
        echo \"\$file_name\" >> ${maven_path}
      fi
      rm -rf ./${tmp_download}
    fi
    mvn -v
  "
  check::exit_code "$?" "maven" "$host 安装maven环境" "exit"
  if [[ "${ADD_USER_TAG:-}" == "1" ]]; then
    command::exec "${host}" "
      sudo chown -R \$(id -u ${ADD_USER_NAME}):\$(id -g ${ADD_USER_NAME}) ${BASE_DIR}/maven
    "
  fi
  log::info "[maven]" "maven环境安装成功!系统环境配置: /etc/profile"
}

# 安装jenkins环境
function init:jenkins() {
  log::info "[jenkins]" "安装jenkins环境..."
  local host="127.0.0.1"
  local tmp_download="tmp_download"
  local tmp_dir="tmp"
  local java_path="${BASE_DIR}/jenkins/install_java.txt"
  local jenkins_path="${BASE_DIR}/jenkins/install_jenkins.txt"
  local java_mem_opts=" -DappName=jenkins -server -Xmx1g"
  local database_opts=" -Ddatabase.codeset=ISO-8859-1 -Ddatabase.logging=false"
  local java_opts_ext=" -Djava.awt.headless=true -Djava.net.preferIPv4Stack=true -Dapplication.codeset=UTF-8 -Dfile.encoding=UTF-8 -Duser.timezone=Asia/Shanghai -Duser.language=C.UTF-8"
  command::exec "${host}" "
    sudo yum install -y fontconfig
    java_bin=\"\"
    jar_file=\"\"
    # 安装JRE
    if [ ! -f "$java_path" ]; then
      mkdir -p ${BASE_DIR}/jenkins
      cd ${BASE_DIR}/jenkins
      rm -rf ./${tmp_download}
      mkdir ./${tmp_download}
      cd ./${tmp_download}
      wget --timeout=10 --waitretry=3 --tries=5 --retry-connrefused --no-check-certificate ${JENKINS_JAVA_URL}
      file_name=\`ls ./ | head -n 1\`
      if [ -z \$file_name ];then
        echo '下载失败=${JENKINS_JAVA_URL}'
        cd ../
      else
        mkdir ./${tmp_dir}
        tar -zxvf \$file_name -C ./${tmp_dir}
        mv \$file_name ../\$file_name
        cd ./${tmp_dir}
        file_name=\`ls ./ | head -n 1\`
        mv \$file_name ../../\$file_name
        cd ../../
        echo \"\$file_name\" >> ${java_path}
        java_bin=\"${BASE_DIR}/jenkins/\$file_name/bin/java\"
        \$file_name/bin/java -version
      fi
      rm -rf ./${tmp_download}
    fi
    # 安装 jenkins
    if [ ! -f "$jenkins_path" ]; then
      mkdir -p ${BASE_DIR}/jenkins
      cd ${BASE_DIR}/jenkins
      rm -rf ./${tmp_download}
      mkdir ./${tmp_download}
      cd ./${tmp_download}
      wget --timeout=10 --waitretry=3 --tries=5 --retry-connrefused --no-check-certificate ${JENKINS_URL}
      file_name=\`ls ./ | head -n 1\`
      if [ -z \$file_name ];then
        echo '下载失败=${JENKINS_URL}'
      else
        mv \$file_name ../\$file_name
        echo \"\$file_name\" >> ${jenkins_path}
        jar_file=\"${BASE_DIR}/jenkins/jenkins.war\"
      fi
      cd ../
      rm -rf ./${tmp_download}
    fi
    # 生成脚本
    if [[ -n \$java_bin && -n \$jar_file ]]; then
      # 写文件start.sh文件
      cat << EOF > ${BASE_DIR}/jenkins/start.sh
#!/bin/bash

httpPort=\\\${1:-'30003'}

#-------------------------------------------------------------------
java='\$java_bin'
jar_file='\$jar_file'
java_mem_opts=' -DappName=jenkins $java_mem_opts'
database_opts='$database_opts'
java_opts_ext='$java_opts_ext'
#-------------------------------------------------------------------

pid=\\\`ps -ef | grep 'DappName=jenkins ' | grep -v 'grep' | awk '{print \\\$2}'\\\`
if [ -z \\\$pid ];then
  nohup \\\$java \\\$java_mem_opts \\\$database_opts \\\$java_opts_ext -jar \\\$jar_file --httpPort=\\\$httpPort >${BASE_DIR}/jenkins/logs.log 2>&1 &
  echo 'jenkins启动成功!'
else
  echo 'jenkins正在运行...'
fi
echo '查看日志:  tail -F ${BASE_DIR}/jenkins/logs.log -n 100'
EOF
      # 写文件kill.sh文件
      cat << EOF > ${BASE_DIR}/jenkins/kill.sh
#!/bin/bash

pid=\\\`ps -ef | grep 'DappName=jenkins ' | grep -v 'grep' | awk '{print \\\$2}'\\\`
if [ -z \\\$pid ];then
  echo 'jenkins未运行'
else
  ps -ef | grep 'DappName=jenkins ' | grep -v 'grep' | awk '{print \\\$2}' | xargs kill
  echo 'jenkins已停止!'
fi
EOF
      chmod +x ${BASE_DIR}/jenkins/start.sh
      chmod +x ${BASE_DIR}/jenkins/kill.sh
    fi
  "
  check::exit_code "$?" "jenkins" "$host 安装jenkins环境" "exit"
  if [[ "${ADD_USER_TAG:-}" == "1" ]]; then
    command::exec "${host}" "
      sudo chown -R \$(id -u ${ADD_USER_NAME}):\$(id -g ${ADD_USER_NAME}) ${BASE_DIR}/jenkins
    "
  fi
  log::info "[jenkins]" "jenkins环境安装成功!"
  log::info "[jenkins]" "启动jenkins: ${BASE_DIR}/jenkins/start.sh 30003"
  log::info "[jenkins]" "停止jenkins: ${BASE_DIR}/jenkins/kill.sh"
}

# 安装redis环境
function init:redis() {
  log::info "[redis]" "安装redis环境..."
  local host="127.0.0.1"
  local tmp_download="tmp_download"
  local tmp_dir="tmp"
  local redis_path="${BASE_DIR}/redis/install_redis.txt"
  command::exec "${host}" "
    if [ ! -d "$redis_path" ]; then
      mkdir -p ${BASE_DIR}/redis
      cd ${BASE_DIR}/redis
      rm -rf ./${tmp_download}
      mkdir ./${tmp_download}
      cd ./${tmp_download}
      wget --timeout=10 --waitretry=3 --tries=5 --retry-connrefused --no-check-certificate ${REDIS_URL}
      file_name=\`ls ./ | head -n 1\`
      if [ -z \$file_name ];then
        echo '下载失败=${REDIS_URL}'
        cd ../
      else
        mkdir ./${tmp_dir}
        tar -zxvf \$file_name -C ./${tmp_dir}
        mv \$file_name ../\$file_name
        cd ./${tmp_dir}
        file_name=\`ls ./ | head -n 1\`
        mv \$file_name ../../\$file_name
        cd ../../
      fi
      rm -rf ./${tmp_download}
      # 编译安装
      if [ -n \$file_name ];then
        yum -y install gcc
        yum -y install centos-release-scl
        yum -y install devtoolset-9-gcc devtoolset-9-gcc-c++ devtoolset-9-binutils
        echo 'source /opt/rh/devtoolset-9/enable' >> /etc/profile
        source /etc/profile
        gcc -v
        redis_install_path=\"${BASE_DIR}/redis/\$file_name-install\"
        mkdir -p \$redis_install_path
        cd \$file_name
        make install PREFIX=\$redis_install_path
        # 写文件start.sh文件
        cat << EOF > \$redis_install_path/redis.conf
# bind 127.0.0.1
protected-mode yes
port 6379
tcp-backlog 511
timeout 300
tcp-keepalive 300
daemonize yes
supervised auto
pidfile \$redis_install_path/redis.pid
loglevel notice
logfile \$redis_install_path/redis.log
databases 16
always-show-logo yes
save 900 1
save 300 10
save 60 10000
stop-writes-on-bgsave-error yes
rdbcompression yes
rdbchecksum yes
dbfilename dump.rdb
rdb-del-sync-files no
dir \$redis_install_path/
replica-serve-stale-data yes
replica-read-only yes
repl-diskless-sync no
repl-diskless-sync-delay 5
repl-diskless-load disabled
repl-disable-tcp-nodelay no
replica-priority 100
acllog-max-len 128
requirepass admin123456
# 限制内存4GB = 4294967296 bytes
maxmemory 4294967296
maxmemory-policy allkeys-lfu
lazyfree-lazy-eviction no
lazyfree-lazy-expire no
lazyfree-lazy-server-del no
replica-lazy-flush no
lazyfree-lazy-user-del no
oom-score-adj no
oom-score-adj-values 0 200 800
appendonly no
appendfilename \"appendonly.aof\"
appendfsync everysec
no-appendfsync-on-rewrite no
auto-aof-rewrite-percentage 100
auto-aof-rewrite-min-size 64mb
aof-load-truncated yes
aof-use-rdb-preamble yes
lua-time-limit 5000
slowlog-log-slower-than 10000
slowlog-max-len 128
latency-monitor-threshold 0
notify-keyspace-events \"\"
hash-max-ziplist-entries 512
hash-max-ziplist-value 64
list-max-ziplist-size -2
list-compress-depth 0
set-max-intset-entries 512
zset-max-ziplist-entries 128
zset-max-ziplist-value 64
hll-sparse-max-bytes 3000
stream-node-max-bytes 4096
stream-node-max-entries 100
activerehashing yes
client-output-buffer-limit normal 0 0 0
client-output-buffer-limit replica 256mb 64mb 60
client-output-buffer-limit pubsub 32mb 8mb 60
hz 10
dynamic-hz yes
aof-rewrite-incremental-fsync yes
rdb-save-incremental-fsync yes
jemalloc-bg-thread yes
EOF
        cat << EOF > \$redis_install_path/start.sh
#!/bin/bash
#set -x
set -e

pid=\\\`ps -ef | grep '\$redis_install_path/bin/redis-server' | grep -v 'grep' | awk '{print \\\$2}'\\\`
cd \$redis_install_path
if [ -z \\\$pid ];then
  \$redis_install_path/bin/redis-server \$redis_install_path/redis.conf
  echo 'redis启动成功!'
else
  echo 'redis正在运行...'
fi
echo '查看日志:  tail -F \$redis_install_path/redis.log -n 100'
EOF
        # 写文件kill.sh文件
        cat << EOF > \$redis_install_path/kill.sh
#!/bin/bash
#set -x
set -e
pid=\\\`ps -ef | grep '\$redis_install_path/bin/redis-server' | grep -v 'grep' | awk '{print \\\$2}'\\\`
if [ -z \\\$pid ];then
  echo 'redis未运行'
else
  ps -ef | grep '\$redis_install_path/bin/redis-server' | grep -v 'grep' | awk '{print \\\$2}' | xargs kill
  echo 'redis已停止!'
fi
EOF
        chmod +x \$redis_install_path/start.sh
        chmod +x \$redis_install_path/kill.sh
      fi
    fi
  "
  check::exit_code "$?" "redis" "$host 安装redis环境" "exit"
  if [[ "${ADD_USER_TAG:-}" == "1" ]]; then
    command::exec "${host}" "
      sudo chown -R \$(id -u ${ADD_USER_NAME}):\$(id -g ${ADD_USER_NAME}) ${BASE_DIR}/redis
    "
  fi
  log::info "[redis]" "redis环境安装成功!"
  log::info "[redis]" "启动redis: ${BASE_DIR}/redis/redis-stable/start.sh"
  log::info "[redis]" "停止redis: ${BASE_DIR}/redis/redis-stable/kill.sh"
}

######################################################################################################
# 主调用逻辑
######################################################################################################
trap trap::info 1 2 3 15 EXIT

# 使用帮助
function help::usage() {
  cat << EOF
Usage:
  env-install-centos.sh [command]

Available Commands:
  init                初始化系统
Flag:
  -update-yum-repos   是否更新yum源, 默认: '1'
  -config             配置系统, 默认: '1'
  -add-user           是否新增用户, 默认: '1'
  -user-name          新增用户名, 默认: 'www'
  -base-dir           新增用户名, 默认: '/opt'
  -git                是否安装git环境, 默认: '1'
  -dstat              是否安装dstat, 默认: '1'
  -htop               是否安装htop, 默认: '1'
  -nginx              是否安装nginx, 默认: '1'
  -nodejs             是否安装nodejs环境, 默认: '1'
  -java               是否安装java环境, 默认: '1'
  -gradle             是否安装gradle环境, 默认: '1'
  -maven              是否安装maven环境, 默认: '1'
  -jenkins            是否安装jenkins环境, 默认: '1'
  -redis              是否安装redis环境, 默认: '1'

Example:
  env-install-centos.sh init \\
    -update-yum-repos 0 \\
    -config 1 \\
    -add-user 1 \\
    -user-name www \\
    -git 1 \\
    -dstat 0 \\
    -htop 0 \\
    -nginx 0 \\
    -nodejs 0 \\
    -java 1 \\
    -gradle 0 \\
    -maven 0 \\
    -jenkins 0 \\
    -redis 0

EOF
  exit 1
}

# 参数处理
[ "$#" == "0" ] && help::usage
while [ "${1:-}" != "" ]; do
  case $1 in
    # -------------------------------------------------------------- 指令
    init  )                 INIT_TAG="1"
                            ;;
    # -------------------------------------------------------------- 指令参数
    -update-yum-repos )     shift
                            UPDATE_YUM_REPOS=${1:-UPDATE_YUM_REPOS}
                            ;;
    -config )               shift
                            CONFIG_TAG=${1:-CONFIG_TAG}
                            ;;
    -add-user )             shift
                            ADD_USER_TAG=${1:-ADD_USER_TAG}
                            ;;
    -user-name )            shift
                            ADD_USER_NAME=${1:-ADD_USER_NAME}
                            ;;
    -base-dir )             shift
                            BASE_DIR=${1:-BASE_DIR}
                            ;;
    -git )                  shift
                            GIT_TAG=${1:-GIT_TAG}
                            ;;
    -dstat )                shift
                            DSTAT_TAG=${1:-DSTAT_TAG}
                            ;;
    -htop )                 shift
                            HTOP_TAG=${1:-HTOP_TAG}
                            ;;
    -nginx )                shift
                            NGINX_TAG=${1:-NGINX_TAG}
                            ;;
    -nodejs )               shift
                            NODEJS_TAG=${1:-NODEJS_TAG}
                            ;;
    -java )                 shift
                            JAVA_TAG=${1:-JAVA_TAG}
                            ;;
    -gradle )               shift
                            GRADLE_TAG=${1:-GRADLE_TAG}
                            ;;
    -maven )                shift
                            MAVEN_TAG=${1:-MAVEN_TAG}
                            ;;
    -jenkins )              shift
                            JENKINS_TAG=${1:-JENKINS_TAG}
                            ;;
    -redis )                shift
                            REDIS_TAG=${1:-REDIS_TAG}
                            ;;
    * )                     help::usage
                            exit 1
  esac
  shift
done

# 开始
log::info "[start]" "bash $0 ${SCRIPT_PARAMETER}"
# 动作
if [[ "${INIT_TAG:-}" == "0" ]]; then
  check::command
  [[ "${UPDATE_YUM_REPOS:-}" == "0" ]] && { init:update_yum_repos; }
  [[ "${CONFIG_TAG:-}" == "0" ]] && { init:config; }
  [[ "${ADD_USER_TAG:-}" == "0" ]] && { init:add_user; }
  [[ "${GIT_TAG:-}" == "0" ]] && { init:git; }
  [[ "${DSTAT_TAG:-}" == "0" ]] && { init:dstat; }
  [[ "${HTOP_TAG:-}" == "0" ]] && { init:htop; }
  [[ "${NGINX_TAG:-}" == "0" ]] && { init:nginx; }
  [[ "${NODEJS_TAG:-}" == "0" ]] && { init:nodejs; }
  [[ "${JAVA_TAG:-}" == "0" ]] && { init:java; }
  [[ "${GRADLE_TAG:-}" == "0" ]] && { init:gradle; }
  [[ "${MAVEN_TAG:-}" == "0" ]] && { init:maven; }
  [[ "${JENKINS_TAG:-}" == "0" ]] && { init:jenkins; }
  [[ "${REDIS_TAG:-}" == "0" ]] && { init:redis; }
else
  help::usage
fi

# bash <(curl -s https://gitee.com/LiZhiW/helm-chart/raw/master/01shell/env-install-centos.sh) [cmd]
